package com.iafme.configuration;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.iafme.dto.req.WebMemberReqDTO;
import com.iafme.model.Member;
import com.iafme.service.IMemberService;
import com.iafme.utils.ConstantsBase;
import com.systemframework.enums.ResultCodeEnum;
import com.systemframework.exception.ResultException;
import com.systemframework.redis.RedisCache;
import com.systemframework.sys.dto.request.LoginRequestDTO;
import com.systemframework.util.MD5;
import com.systemframework.util.PatternUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author summer
 * @version 1.0
 * @date 2025/1/21 19:13
 */
@Component
@AllArgsConstructor
public class LoginConfiguration {


   private final IMemberService memberService;
   private final RedisCache redisCache;
   private final CodeGenerator codeGenerator;

    public SaTokenInfo login(LoginRequestDTO loginReqDTO) {
        String captchaCode = this.redisCache.get(ConstantsBase.VERIFICATION_CODE + loginReqDTO.getCaptchaKey());
        if (StrUtil.isEmpty(captchaCode)) {
            throw new ResultException("验证码已过期,刷新验证码");
        } else if (!this.codeGenerator.verify(captchaCode, loginReqDTO.getCaptchaCode())) {
            throw new ResultException("验证码输入错误,请重新输入");
        }else {

            LambdaQueryWrapper<Member> lambdaQueryWrapper = Wrappers.lambdaQuery(Member.class);
            if(PatternUtil.isEmail(loginReqDTO.getUsername())){
                lambdaQueryWrapper.eq(Member::getEmail,loginReqDTO.getUsername());
            }else if(PatternUtil.isPhone(loginReqDTO.getUsername())){
                lambdaQueryWrapper.eq(Member::getPhone,loginReqDTO.getUsername());
            }else{
                lambdaQueryWrapper.eq(Member::getUsername,loginReqDTO.getUsername());
            }
            Member member = memberService.getOne(lambdaQueryWrapper);
           if(ObjectUtil.isNotEmpty(member) && MD5.aesEncrypt(member.getEmail(), loginReqDTO.getPassword()).equals(member.getPassword())){
               StpUtil.login(member.getId(),"WEB");
               SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
               if(StrUtil.isNotEmpty(SaManager.getConfig().getTokenPrefix())){
                   tokenInfo.setTokenValue(SaManager.getConfig().getTokenPrefix()+" "+tokenInfo.getTokenValue());
               }
               return tokenInfo;
           }else{
               throw new ResultException(ResultCodeEnum.ERROR_USER_NAME_PASS.msg());

           }
        }

    }


    public void reg(WebMemberReqDTO memberReqDTO){
        checkCode(memberReqDTO);
        LambdaQueryWrapper<Member> wrapper = Wrappers.lambdaQuery(Member.class).eq(Member::getEmail, memberReqDTO.getEmail());
        Member one = memberService.getOne(wrapper);
        if(ObjectUtil.isNotEmpty(one)){
            throw new ResultException("用户已存在,请登录");
        }
        String random = RandomUtil.randomString("0123456789",8);
        String password=MD5.aesEncrypt(memberReqDTO.getEmail(), memberReqDTO.getPassword());
        Member member=new Member();
        member.setEmail(memberReqDTO.getEmail());
        member.setPassword(password);
        member.setIgAasId(random);
        member.setCreateTime(LocalDateTime.now());
        memberService.save(member);
    }

    private void checkCode(WebMemberReqDTO reqDTO){
        String code = redisCache.get(ConstantsBase.EMAIL_CODE + reqDTO.getEmail());
        if(StrUtil.isEmpty(code)){
            throw new ResultException("验证码已过期,请重新刷新验证码");
        }else if(!code.equals(reqDTO.getCode())){
            throw new ResultException("验证码输入错误,请重新输入");
        }
        if(!reqDTO.getPassword().equals(reqDTO.getConfirmPsd())){
            throw new ResultException("两次密码输入不一样,请重新输入");
        }
    }

    public void modifyPsd(WebMemberReqDTO memberReqDTO) {
        checkCode(memberReqDTO);
        LambdaQueryWrapper<Member> wrapper = Wrappers.lambdaQuery(Member.class).eq(Member::getEmail, memberReqDTO.getEmail());
        Member member = memberService.getOne(wrapper, false);
        if(ObjectUtil.isEmpty(member)){
            throw new ResultException("电子邮箱不存在,请重新注册");
        }
        String password=MD5.aesEncrypt(memberReqDTO.getEmail(), memberReqDTO.getPassword());
        member.setPassword(password);
        memberService.updateById(member);
    }
}
